#include "bsp_timer.h"
#include "stm32f10x_tim.h"
#include "stm32f10x_rcc.h"
#include "misc.h"
#include "stm32f10x.h"

#define BSP_TIMER_USER_SYSTICK_TYPE         (TIM2)
#define BSP_TIMER_USER_SYSTICK_RCC          (RCC_APB1Periph_TIM2)
#define BSP_TIMER_USER_SYSTICK_IRQN         (TIM2_IRQn)
#define BSP_TINER_USER_SYSTICK_PRESCALER    (72 - 1)
#define BSP_TINER_USER_SYSTICK_PERIOD       (1000u)



static void bsp_timer_2_init(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    /* 1. 初始化时钟 */
    RCC_APB1PeriphClockCmd(BSP_TIMER_USER_SYSTICK_RCC, ENABLE); 
    /* 2. 初始化定时器参数,设置自动重装值，分频系数，计数方式等 */
    TIM_TimeBaseStructure.TIM_Period = BSP_TINER_USER_SYSTICK_PERIOD;
    TIM_TimeBaseStructure.TIM_Prescaler =BSP_TINER_USER_SYSTICK_PRESCALER; 
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; 
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(BSP_TIMER_USER_SYSTICK_TYPE, &TIM_TimeBaseStructure);
    /* 3. 设置 TIM3_DIER 允许更新中断 */
    TIM_ITConfig(BSP_TIMER_USER_SYSTICK_TYPE, TIM_IT_Update, ENABLE);
    /* 4. TIM3 中断优先级设置。 */
    
    NVIC_InitStructure.NVIC_IRQChannel = BSP_TIMER_USER_SYSTICK_IRQN; //TIM3 中断
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //先占优先级 0 级
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //从优先级 3 级
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ 通道被使能
    NVIC_Init(&NVIC_InitStructure); //初始化 NVIC 寄存器
    /* 5. 使能定时器2 */
    TIM_Cmd(BSP_TIMER_USER_SYSTICK_TYPE, ENABLE);
}

// /* 6. 编写中断服务函数 */
// void bsp_timer_user_systick_isr_process(void) //TIM3 中断
// {
//     if (TIM_GetITStatus(BSP_TIMER_USER_SYSTICK_TYPE, TIM_IT_Update) != RESET)
//     {
//         // 硬件置了1，需要软件来清0
//         TIM_ClearITPendingBit(BSP_TIMER_USER_SYSTICK_TYPE, TIM_IT_Update);
//         /* add your code here */
        
//     }
// }
void bsp_timer_init(void)
{
    bsp_timer_2_init();
}
